package com.shbaiche.bifenba.ui.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.adapter.home.HomeGridMatchAdapter;
import com.shbaiche.bifenba.adapter.home.HomeInfoAdapter;
import com.shbaiche.bifenba.adapter.video.VideoAdapter;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.data.CompeteVo;
import com.shbaiche.bifenba.model.match.MatchesVo;
import com.shbaiche.bifenba.model.video.ArticleListMessage;
import com.shbaiche.bifenba.model.video.ArticleVo;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.base.BaseFragment;
import com.shbaiche.bifenba.ui.base.WebActivity;
import com.shbaiche.bifenba.ui.video.VideoDetailActivity;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xstatecontroller.XStateController;
import me.militch.widget.bannerholder.BannerClickListener;
import me.militch.widget.bannerholder.BannerHolderView;
import me.militch.widget.bannerholder.HolderAttr;
import me.militch.widget.bannerholder.ImageViewBannerLoader;
import me.militch.widget.bannerholder.loader.SimpleImageLoader;
import okhttp3.Call;

public class HomeFragment extends BaseFragment {

    private static final String ARG_POSITION = "position";

    private RecyclerView recyclerMatch, recyclerInfo;

    @BindView(R.id.layout_home)
    LinearLayout layout;

    SwipeRefreshLayout swipeRefreshLayout;
    XStateController contentLayout;
    BannerHolderView bannerHolderView;
    HomeGridMatchAdapter matchAdapter;
    HomeInfoAdapter adapter;
    View matchView;

    private Long typeId;
    List<String> integers;

    // 资讯、视频列表
    private List<ArticleVo> bannerList;

    HolderAttr holder;

    private int index = 0;

    public HomeFragment() {

    }

//    public static HomeFragment newInstance(int position) {
//        HomeFragment f = new HomeFragment(typeId);
//        Bundle b = new Bundle();
//        b.putInt(ARG_POSITION, position);
//        f.setArguments(b);
//        return f;
//    }


    private void load() {
        ArticleListMessage msg = new ArticleListMessage();
//        msg.setType(ArticleGroupVo.Type.VIDEO);
        msg.setGroupId(typeId);
        msg.setPageIndex(index);
        msg.setPageSize(50);

        NetApi.videoList(msg, new JsonCallback<TransMessage>() {

            @Override
            public void onFail(Call call, Exception e, int id) {
                contentLayout.showContent();
                if (swipeRefreshLayout != null)
                    swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                contentLayout.showContent();
                ToastUtil.show("onFail" + e.getMessage());
                if (swipeRefreshLayout != null)
                    swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onResponse(TransMessage response, int id) {

                if (swipeRefreshLayout != null)
                    swipeRefreshLayout.setRefreshing(false);
                contentLayout.showContent();

                Gson gson = new Gson();
                ArticleListMessage msg = gson.fromJson(response.getMessage(), ArticleListMessage.class);

                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {

                    bannerList = msg.getBannerList();

                    if (integers == null) {
                        integers = new ArrayList<>();
                        List<ArticleVo> bannerList = msg.getBannerList();
                        if (bannerList != null) {
                            for (int i = 0; i < bannerList.size(); i++) {
                                ArticleVo vo = bannerList.get(i);
                                List<String> banner = vo.getImgUrl();
                                if (banner != null && banner.size() > 0) {
                                    integers.add(banner.get(0));
                                }
                            }
                        }
                        if (integers.size() > 0) {
                            bannerHolderView.setVisibility(View.VISIBLE);
                        }
                        initBan();
                    }
                    List<MatchesVo> matchList = msg.getMatchesList();
                    if (matchList != null) {
                        if (matchAdapter == null) {
                            matchAdapter = new HomeGridMatchAdapter(getActivity(), matchList);
                            recyclerMatch.setAdapter(matchAdapter);
                        } else {
                            matchAdapter.setData(matchList);
                        }
                    }
                    if (matchList == null || matchList.size() == 0) {
                        recyclerMatch.setVisibility(View.GONE);
                        matchView.setVisibility(View.GONE);
                    }

                    List<ArticleVo> listData = msg.getList();
                    if (adapter == null) {
                        adapter = new HomeInfoAdapter(getActivity(), listData);
                        recyclerInfo.setAdapter(adapter);
                    } else {
                        adapter.setData(listData);
                    }

                    if (msg.getSearch() != null && !TextUtils.isEmpty(msg.getSearch())) {
                        Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                        intent.putExtra("search", msg.getSearch());
                        getActivity().sendBroadcast(intent);
                    }
//                    adapter = new VideoAdapter(getActivity(), suData, list, R.layout.adapter_video_item);
//                    listView.setAdapter(adapter);

                } else {


                }

            }
        });
    }

    private void initBan() {
        holder = HolderAttr.builder()
                //加载资源集合
                .

                        setBanners(integers)
                //是否自动轮播
                .

                        setAutoLooper(true)
                //设置轮播时间（单位：毫秒）
                .

                        setLooperTime(3000)
                .

                        setIndicatorResId(R.drawable.banner_holder_selector2)
                //设置切换时长（单位：毫秒）
                .

                        setSwitchDuration(800)
                //设置Banner点击事件
                .

                        setBannerClickListener(new BannerClickListener() {
                            @Override
                            public void onBannerClick(int p) {
                                //点击位置索引 0~
                                if (bannerList != null && bannerList.size() > 0) {
//                                    Bundle b = new Bundle();
//                                    b.putLong("id", bannerList.get(p).getId());
//                                    b.putString("type", "资讯");
//                                    VideoDetailActivity.launch(getActivity(), b);
                                    WebActivity.launch(getActivity(), bannerList.get(p).getDetailUrl(), "资讯详情", bannerList.get(p).getId().intValue());
                                }
                            }
                        })
                //设置Banner图片加载器可以使用图片加载框架
                .

                        setBannerLoader(new ImageViewBannerLoader() {
                            @Override
                            public void loadImage(Context context, Object path, ImageView view) {
                        /* 提供参数与控件，自定加载图片的实现方式
                         * -选择使用默认提供的ImageLoader加载图片
                         */
                                SimpleImageLoader.getInstence().loadImage((String) path, view);
                            }

                            @Override
                            public ImageView createView(Context context) {
                                ImageView imageView = new ImageView(context);
                                imageView.setBackgroundResource(R.drawable.defult);
                                return imageView;
                            }
                        }).

                        builder(bannerHolderView);
        try {
            if (!isPause) {
                if (holder != null)
                    holder.start();
            }
        } catch (Exception e) {

        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            try {
                if (holder != null)
                    holder.start();
                isPause = false;
            } catch (Exception e) {

            }
        } else {
        }
    }


    boolean isPause = false;

    @Override
    public void onPause() {
        isPause = true;
        super.onPause();
    }

    private void initRefreshLayout() {
        swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                index = 0;
                load();
            }
        });

    }

    private void initContentLayout() {
        contentLayout.loadingView(View.inflate(getActivity(), R.layout.view_loading, null));
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.containsKey("data")) {
            typeId = savedInstanceState.getLong("data");
        } else {
            typeId = getArguments().getLong("data");
        }

        bannerHolderView = (BannerHolderView) layout.findViewById(R.id.banner_holder);

        recyclerMatch = (RecyclerView) layout.findViewById(R.id.home_recy_match);
        matchView = layout.findViewById(R.id.home_recy_match_view);
        recyclerMatch.setLayoutManager(new

                GridLayoutManager(getActivity(), 2));

        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL);
        divider.setDrawable(ContextCompat.getDrawable(

                getActivity(), R.drawable.custom_divider_h));
        recyclerMatch.addItemDecoration(divider);

        recyclerInfo = (RecyclerView) layout.findViewById(R.id.home_recy_info);
        //创建LinearLayoutManager 对象
        LinearLayoutManager layoutmanager = new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        layoutmanager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerInfo.setLayoutManager(layoutmanager);


        swipeRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.swipeRefreshLayout);
        contentLayout = (XStateController) layout.findViewById(R.id.contentLayout);

        initRefreshLayout();

        initContentLayout();

        if (contentLayout != null) {
            contentLayout.showLoading();
        }
        load();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }
}